# -*- coding: utf-8 -*-
from decimal import Decimal
from dtrader.broker import BaseBroker
from smtplib import SMTP_SSL
from email.header import Header
from email.mime.text import MIMEText
from dtrader import logger
from dtrader.event import FillEvent

class MailBroker(BaseBroker):

    def __init__(self,mail_to_list,events_queue):
        self.__mail_to_list = mail_to_list
        self.__logger = logger.getLogger("MAIL broker")
        self.events_queue = events_queue

    mailInfo = {
        "from": "hezhenke123@163.com",
        "to": "hezhenke123@163.com",
        "hostname": "smtp.163.com",
        "username": "hezhenke123@163.com",
        "password": "hezhenke@163.com",
        "mailencoding": "utf-8"
    }

    def send_mail(self,to_list,sub,content):  #to_list：收件人；sub：主题；content：邮件内容
        smtp = SMTP_SSL(self.mailInfo["hostname"])
        smtp.ehlo(self.mailInfo["hostname"])
        smtp.login(self.mailInfo["username"], self.mailInfo["password"])
        msg = MIMEText(content, "plain", self.mailInfo["mailencoding"])
        msg["Subject"] = Header(sub, self.mailInfo["mailencoding"])
        msg["from"] = self.mailInfo["from"]
        msg["to"] = ";".join(to_list)
        smtp.sendmail(self.mailInfo["from"], self.mailInfo["to"], msg.as_string())
        smtp.quit()

    def create_limit_order(self,ticker,action,quantity,limit_price):
        order = "LIMIT ORDER ticker:%s,action:%s,quantity:%s,limit_price:%s"%(ticker,action,quantity,limit_price)
        self.__logger.info(order)
        fev = FillEvent(ticker, action, quantity, "SH", limit_price, Decimal("0.1"))
        self.events_queue.put(fev)
        return order
    def create_market_order(self,ticker,action,quantity):
        order = "MARKET ORDER ticker:%s,action:%s,quantity:%s" % (ticker, action, quantity)
        self.__logger.info(order)
        return order
    def submit_order(self,order):
        content = order
        self.send_mail(self.__mail_to_list,u"自动化交易提醒",content)

    def get_positions_from_broker(self):
        return []

    def get_cash(self):
        return 10000;